import axios from 'axios'
import utils from './utils';
import router from '../router'
const request = axios.create({
    //baseURL: import.meta.env.VITE_APP_BASE_API,
    baseURL: import.meta.env.VITE_APP_API_BASE_URL + import.meta.env.VITE_APP_API_PREFIX,
    timeout: 20000,
})
// 添加请求拦截器
request.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    config.headers.Authorization = utils.getToken() || '';
    return config;
}, function (error) {
    // 对请求错误做些什么
    console.log(error);
    return Promise.reject(error);
});

// 添加响应拦截器
request.interceptors.response.use(function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    if (response.data.code === 403) {
        utils.showMessage(response.data.message, 'error', 2000);
        return Promise.reject(response.data.message + "Unauthorized");
    }
    if (response.data.code === 405) {
        utils.showMessage(response.data.message, 'error', 2000);
        return Promise.reject(response.data.message + "Error 405");
    }
    if (response.data.code === 401) {
        utils.showMessage(response.data.message, 'error', 2000);
        utils.removeToken();
        if (router.currentRoute.path !== '/login') {
            setTimeout(() => {
                router.push('/login');
            }, 1000)
        }
        // 阻止继续传递响应
        return Promise.reject(new Error('Unauthorized'));

    }
    return response;
}, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
});
export const get = (url, params) => request.get(url, { params }).then(response => response.data).catch(error => {
    console.log(error)
})
export const post = (url, params) => request.post(url, params).then(response => response.data).catch(error => {
    console.log(error)
})
export const put = (url, params) => request.put(url, params).then(response => response.data).catch(error => {
    console.log(error)
})

export const patch = (url, params, config) => request.patch(url, params, config).then(response => response.data).catch(error => {
    console.log(error)
})
export const del = (url, params) => request.delete(url, { params }).then(response => response.data).catch(error => {
    console.log(error)
})

export default request